package com.lzy.netty.http;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

/**
 * @author lzy
 * @date 2025/8/26 16:05
 * @description http处理类
 **/

//SimpleChannelInboundHandler<HttpObject> 泛型参数表示处理什么类型的数据
public class HttpHandler extends SimpleChannelInboundHandler<HttpObject> {

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext,
                                HttpObject httpObject) throws Exception {

        // 获取channel
        Channel channel = channelHandlerContext.channel();

        // 打印客户端远程地址
        System.out.println("客户端远程地址：" + channel.remoteAddress());

        // 通过缓冲区来定义发送的消息，读写数据都是通过缓冲区来完成
        ByteBuf content = Unpooled.copiedBuffer("Hello World", CharsetUtil.UTF_8);

        // 构建http的response
        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                                                                HttpResponseStatus.OK,
                                                                content);
        response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
        response.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes());

        // 将response返回给客户端
        channelHandlerContext.writeAndFlush(response);
    }


}
